用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

示例 1:

输入: ["CQueue","appendTail","deleteHead","deleteHead"] [[],[3],[],[]] 输出:[null,null,3,-1] 示例 2:

输入: ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"] [[],[],[5],[2],[],[]] 输出:[null,-1,null,null,5,2]

代码

var CQueue = function(){
    this.stackA = []; //入队栈 
    this.stackB = []; //出队栈
}
CQueue.prototype.appendTail = function(value){
    this.stackA.push(value);
}
CQueue.prototype.deleteHead = function(){
    if(this.stackB.length){
      // 出栈优先考虑是否有数据
        return this.stackB.pop();
    }else{
        // 入栈,将A pop 移除并push到B中
        while(this.stackA.length){
            this.stackB.push(this.stackA.pop());
        }
        // 若B中无数据,从入栈中倒入B中
        if(!this.stackB.length){
            return -1;
        }else{
            return this.stackB.pop();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
最后更新时间: 6/20/2022, 10:48:50 PM